/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SubsitemaAgenda;

import SubsistemaPaciente.DialogoInfoPaciente;
import clienteSandraParada.Login;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import service.Cita;
import service.ProgramaMedicoFonasa;

/**
 *Clase que extiende de jDialog que se encarga de recibir los datos para agregar una cita
 * @author Mario
 */
public class DialogoAgregarCita extends javax.swing.JDialog {

    private Dia dia;
    private Semana semana;
    private String tipo;
    private int day;
    public boolean isAgregadaExitosamente;
    int contador;
    service.HorarioProfesional horario;
    /*
     * Constructor de la clase
     */

    public DialogoAgregarCita(Dia dia, Semana semana, String tipo, service.HorarioProfesional horario) {
        //super(new JFrame(), false);
        this.setTitle("Agregar Cita");
        this.dia = dia;
        this.semana = semana;
        this.tipo = tipo;
        this.horario = horario;
        this.isAgregadaExitosamente = false;
                
        contador = 0;
        initComponents();
        setIconImage(new ImageIcon(getClass().getResource("/GUI/Img/logo2.png")).getImage());        
        normalizarMensajeria();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(screenSize.width / 2 - (this.getWidth() / 2),
                screenSize.height / 2 - (this.getHeight() / 2));

        if (tipo.equals("Dia")) {
            try {
                GregorianCalendar cal = new GregorianCalendar();
                cal.setTime(dia.jCalendar1.getDate());
                XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
                service.HorarioProfesional h = (service.HorarioProfesional) cargarHorarioSegunFecha(calendar, dia.profesional.getRut());              
                campoFecha.setDate(dia.jCalendar1.getDate());                
                formatoHora(h.getDuracionBloque(), (String) dia.jTable1.getValueAt(dia.jTable1.getSelectedRow(), 0));
            } catch (DatatypeConfigurationException ex) {
                Logger.getLogger(DialogoAgregarCita.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (tipo.equals("Semana")) {
            try {
                GregorianCalendar cal = new GregorianCalendar();
                cal.setTime(semana.jCalendar1.getDate());
                XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
                service.HorarioProfesional h = (service.HorarioProfesional) cargarHorarioSegunFecha(calendar, semana.getProfesional().getRut());
                
                int diaCalendar = semana.jCalendar1.getCalendar().get(Calendar.DAY_OF_WEEK)-1;
                int diaTabla = semana.jTable1.getSelectedColumn();                
                int diferencia =diaTabla-diaCalendar;                ;
                Calendar nextDate = new GregorianCalendar();
                nextDate.setTime(semana.jCalendar1.getDate());
                nextDate.add(Calendar.DAY_OF_MONTH, diferencia);
                campoFecha.setDate(nextDate.getTime());                                
                formatoHora(h.getDuracionBloque(), (String) semana.jTable1.getValueAt(semana.jTable1.getSelectedRow(), 0));
            }  catch (DatatypeConfigurationException ex) {
                Logger.getLogger(DialogoAgregarCita.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        rutFocus();
        DialogoBuscarPaciente diag = new DialogoBuscarPaciente(null, true, this);
        diag.setLocationRelativeTo(null);
        diag.setVisible(true);        
        campoRutPaciente.getRut().requestFocus();
        desactivaCheckPopups();                
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDayChooser1 = new com.toedter.calendar.JDayChooser();
        jLabel12 = new javax.swing.JLabel();
        jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        campoHora = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        campoMinuto = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        campoEstado = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        campoNumeroSesion = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        campoNombrePaciente = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        campoRutPaciente = new componentes.Rut();
        jLabel11 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        campoMensajeria = new javax.swing.JLabel();
        jLabel24 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        campoProgramaMedico = new javax.swing.JComboBox();
        lunes = new javax.swing.JCheckBox();
        martes = new javax.swing.JCheckBox();
        miercoles = new javax.swing.JCheckBox();
        sabado = new javax.swing.JCheckBox();
        jueves = new javax.swing.JCheckBox();
        viernes = new javax.swing.JCheckBox();
        botonCrearPrograma = new javax.swing.JButton();
        campoFecha = new com.toedter.calendar.JDateChooser();

        jLabel12.setText("*");

        jCheckBoxMenuItem1.setSelected(true);
        jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Fecha:");

        jLabel2.setText("Desde:");

        campoHora.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" }));
        campoHora.setEnabled(false);

        jLabel4.setText(":");

        campoMinuto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "00", "05", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55" }));
        campoMinuto.setEnabled(false);

        jLabel6.setText("Paciente:");

        jLabel8.setText("Estado:");

        campoEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "No Confirmada", "Confirmada" }));

        jLabel9.setText("Número sesión:");

        campoNumeroSesion.setEditable(false);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setBorder(javax.swing.BorderFactory.createTitledBorder("Comentario"));
        jScrollPane1.setViewportView(jTextArea1);

        campoNombrePaciente.setEnabled(false);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Cancelar.png"))); // NOI18N
        jButton1.setText("Cancelar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Agregar.png"))); // NOI18N
        jButton2.setText("Agregar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarCita(evt);
            }
        });

        jLabel10.setText("Rut paciente:");

        jLabel11.setText("*");

        jLabel14.setText("*");

        campoMensajeria.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        campoMensajeria.setText("Área de mensajería");

        jLabel24.setText("Campos obligatorios *");

        jLabel3.setText("Repetir");

        jLabel5.setText("Programa");

        campoProgramaMedico.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Sin programa" }));
        campoProgramaMedico.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                campoProgramaMedicoMouseEntered(evt);
            }
        });
        campoProgramaMedico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                campoProgramaMedicoActionPerformed(evt);
            }
        });
        campoProgramaMedico.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                campoProgramaMedicoFocusGained(evt);
            }
        });

        lunes.setText("Lunes");
        lunes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lunesActionPerformed(evt);
            }
        });

        martes.setText("Martes");
        martes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                martesActionPerformed(evt);
            }
        });

        miercoles.setText("Miercoles");
        miercoles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miercolesActionPerformed(evt);
            }
        });

        sabado.setText("Sabado");
        sabado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sabadoActionPerformed(evt);
            }
        });

        jueves.setText("Jueves");
        jueves.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                juevesActionPerformed(evt);
            }
        });

        viernes.setText("Viernes");
        viernes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viernesActionPerformed(evt);
            }
        });

        botonCrearPrograma.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Protocolo.png"))); // NOI18N
        botonCrearPrograma.setText("Crear");
        botonCrearPrograma.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonCrearProgramaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(campoMensajeria, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel24, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(24, 24, 24)
                                .addComponent(campoNombrePaciente, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel10)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(campoRutPaciente, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel11))
                                    .addComponent(campoFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(campoHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(campoMinuto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel14))))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel8)
                                    .addComponent(jLabel5))
                                .addGap(23, 23, 23)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(campoEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(campoProgramaMedico, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(botonCrearPrograma))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(lunes)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(martes)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(miercoles))
                                    .addComponent(campoNumeroSesion, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(2, 2, 2)
                                        .addComponent(jueves)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(viernes)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(sabado))))
                            .addComponent(jLabel3)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButton2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jButton1))
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(campoFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(campoHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)
                        .addComponent(campoMinuto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel14)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel10)
                    .addComponent(campoRutPaciente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(campoNombrePaciente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(campoEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoProgramaMedico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(botonCrearPrograma))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(campoNumeroSesion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lunes)
                    .addComponent(martes)
                    .addComponent(miercoles))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 2, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jueves)
                    .addComponent(viernes)
                    .addComponent(sabado))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel24)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(campoMensajeria))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    /*
     * Metodo para agregar una cita al sistema, se obtienen los valores y se agrega una tupla de cita en la BD
     */
    private void guardarCita(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarCita
        if (camposValidos()) {
            ArrayList<Date> dates = calculaFechasDeCitas();
            int desdeHora = Integer.parseInt((String) this.campoHora.getSelectedItem());
            int desdeMinuto = Integer.parseInt((String) this.campoMinuto.getSelectedItem());            
            String numeroSesion = "0" + this.campoNumeroSesion.getText();
            String estado = this.campoEstado.getSelectedItem() + "";
            String comentario = this.jTextArea1.getText();
            String valorNuevo = "";
            for (int i = 0; i < dates.size(); i++) {                
                if (tipo.equals("Dia")) {
                    if (!isPacienteEnlazadoAProfesional(campoRutPaciente.getRut().getText(), dia.profesional.getRut())) {
                        agregarEnlaceProfesionalPaciente(dia.profesional.getRut(), campoRutPaciente.getRut().getText());
                    }                    
                        try {
                            service.Cita cita = new service.Cita();
                            cita.setRutProfesional(dia.getProfesional().getRut());                        
                            cita.setRutPaciente(this.campoRutPaciente.getRut().getText());                                                    
                            GregorianCalendar c = new GregorianCalendar();            
                            c.setTime(dates.get(i));
                            XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);   
                            cita.setFecha(calendar);
                            cita.setDesdeHora(desdeHora);
                            cita.setDesdeMinuto(desdeMinuto);
                            cita.setNumeroSesion(Integer.parseInt(numeroSesion));
                            cita.setObservacion(comentario);
                            cita.setEstado(estado);
                            cita.setVisible(true);
                            cita = agregarProgramaMedico(cita);
                            Long id = agregarCita(cita);
                            cita.setId(id);
                            if (dia.jCalendar1.getDate().equals(dates.get(i))) 
                                dia.addCita(cita);
                            System.err.println("ID CITA = "+cita.getId());
                            valorNuevo = "Rut profesional:" + cita.getRutProfesional() + "\n" + "rut Paciente: " + cita.getRutPaciente()
                                    + "\n" + "Fecha: " +cita.getFecha() + "\n" + "Desde hora: " + cita.getDesdeHora()
                                    + "\n" + "Desde minuto: " + cita.getDesdeMinuto() + "\n" + "Número sesiones: " + cita.getNumeroSesion() + "\n" + "Observación: " + cita.getObservacion()
                                    + "\n" + "Estado: " + cita.getEstado();
                            registrar(Login.getUser(), "Agenda", "Agregó cita a profesional:" + cita.getRutProfesional()+"de paciente :"+cita.getRutPaciente(), "No aplica", valorNuevo);
                        } catch (DatatypeConfigurationException ex) {
                            Logger.getLogger(DialogoAgregarCita.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    Object o = dia.jTable1.getValueAt(dia.jTable1.getSelectedRow(), dia.jTable1.getSelectedColumn());                    
                    if( o instanceof ArrayList) {
                        dia.mostrarPanelCita((ArrayList)o);                        
                    }
                        
                        
                        
                    
                    this.isAgregadaExitosamente = true;
                }
                if (tipo.equals("Semana")) {
                    try {
                        if (!isPacienteEnlazadoAProfesional(campoRutPaciente.getRut().getText(), semana.profesional.getRut())) {
                            agregarEnlaceProfesionalPaciente(semana.profesional.getRut(), campoRutPaciente.getRut().getText());
                        }                    
                        service.Cita cita = new service.Cita();
                        cita.setRutProfesional(semana.getProfesional().getRut());                    
                        cita.setRutPaciente(this.campoRutPaciente.getRut().getText());                    
                        GregorianCalendar c = new GregorianCalendar();            
                        c.setTime(dates.get(i));
                        XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);   
                        cita.setFecha(calendar);                    
                        cita.setDesdeHora(desdeHora);
                        cita.setDesdeMinuto(desdeMinuto);
                        cita.setNumeroSesion(Integer.parseInt(numeroSesion));
                        cita.setObservacion(comentario);
                        cita.setEstado(estado);
                        cita.setVisible(true);
                        cita = agregarProgramaMedico(cita);
                        Long id = agregarCita(cita);
                        cita.setId(id);
                        semana.addCita(cita);
                        //}
                        this.isAgregadaExitosamente = true;
                        valorNuevo = "Rut profesional:" + cita.getRutProfesional() + "\n" + "rut Paciente: " + cita.getRutPaciente()
                                + "\n" + "Fecha: "+ cita.getFecha() + "\n" + "Desde hora: " + cita.getDesdeHora()
                                + "\n" + "Desde minuto: " + cita.getDesdeMinuto() + "\n" + "Número sesiones: " + cita.getNumeroSesion() + "\n" + "Observación: " + cita.getObservacion()
                                + "\n" + "Estado: " + cita.getEstado();
                        registrar(Login.getUser(), "Agenda", "Agregó cita a profesional:" + cita.getRutProfesional()+"de paciente :"+cita.getRutPaciente(), "No aplica", valorNuevo);
                    } catch (DatatypeConfigurationException ex) {
                        Logger.getLogger(DialogoAgregarCita.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    Object o = semana.jTable1.getValueAt(semana.jTable1.getSelectedRow(), semana.jTable1.getSelectedColumn());                    
                    if( o instanceof ArrayList) {
                        semana.mostrarPanelCita((ArrayList)o);                        
                    }
                }
            }
            
            this.dispose();
        }
    }//GEN-LAST:event_guardarCita

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void lunesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lunesActionPerformed
        if (lunes.isSelected()) {
            contador++;
        } else {
            contador--;
        }
        if (contador == Integer.parseInt(campoNumeroSesion.getText()) - 1) {
            desactivaCheckPopups();
        } else {
            activaCheckPopups();
        }
    }//GEN-LAST:event_lunesActionPerformed

    private void martesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_martesActionPerformed
        if (martes.isSelected()) {
            contador++;
        } else {
            contador--;
        }
        if (contador == Integer.parseInt(campoNumeroSesion.getText()) - 1) {
            desactivaCheckPopups();
        } else {
            activaCheckPopups();
        }
    }//GEN-LAST:event_martesActionPerformed

    private void miercolesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miercolesActionPerformed
        if (miercoles.isSelected()) {
            contador++;
        } else {
            contador--;
        }
        if (contador == Integer.parseInt(campoNumeroSesion.getText()) - 1) {
            desactivaCheckPopups();
        } else {
            activaCheckPopups();
        }
    }//GEN-LAST:event_miercolesActionPerformed

    private void juevesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_juevesActionPerformed
        if (jueves.isSelected()) {
            contador++;
        } else {
            contador--;
        }
        if (contador == Integer.parseInt(campoNumeroSesion.getText()) - 1) {
            desactivaCheckPopups();
        } else {
            activaCheckPopups();
        }
    }//GEN-LAST:event_juevesActionPerformed

    private void viernesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viernesActionPerformed
        if (viernes.isSelected()) {
            contador++;
        } else {
            contador--;
        }
        if (contador == Integer.parseInt(campoNumeroSesion.getText()) - 1) {
            desactivaCheckPopups();
        } else {
            activaCheckPopups();
        }
    }//GEN-LAST:event_viernesActionPerformed

    private void sabadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sabadoActionPerformed
        contador++;
        if (contador == Integer.parseInt(campoNumeroSesion.getText()) - 1) {
            desactivaCheckPopups();
        } else {
            activaCheckPopups();
        }
    }//GEN-LAST:event_sabadoActionPerformed

    private void botonCrearProgramaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCrearProgramaActionPerformed
        DialogoTipoPrograma d = new DialogoTipoPrograma(null, true,this.campoRutPaciente.getRut().getText());
        d.setAlwaysOnTop(true);
        d.setLocationRelativeTo(null);
        d.setVisible(true);        
    }//GEN-LAST:event_botonCrearProgramaActionPerformed

    private void campoProgramaMedicoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_campoProgramaMedicoFocusGained
        cargarProgramas();
    }//GEN-LAST:event_campoProgramaMedicoFocusGained

    private void campoProgramaMedicoMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_campoProgramaMedicoMouseEntered
                
    }//GEN-LAST:event_campoProgramaMedicoMouseEntered

    private void campoProgramaMedicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoProgramaMedicoActionPerformed
        Object o = campoProgramaMedico.getSelectedItem();
        if(o instanceof service.ProgramaMedicoFonasa){
            service.ProgramaMedicoFonasa programa = (service.ProgramaMedicoFonasa) o;   
            campoNumeroSesion.setText(programa.getCantidadCitasTotal()-programa.getCantidadCitas()+1+"");
        }
        else if(o instanceof service.ProgramaDipreca){
            service.ProgramaDipreca programa = (service.ProgramaDipreca) o;
            campoNumeroSesion.setText(programa.getCantidadCitasTotal()-programa.getCantidadCitas()+1+"");
        }
        else if(o instanceof service.ProgramaMedicoJeafosale){
            service.ProgramaMedicoJeafosale programa = (service.ProgramaMedicoJeafosale) o;
            campoNumeroSesion.setText(programa.getCantidadCitasTotal()-programa.getCantidadCitas()+1+"");
        }
        else
            campoNumeroSesion.setText("0");
        
    }//GEN-LAST:event_campoProgramaMedicoActionPerformed
    
    private void rutFocus() {
        campoRutPaciente.getRut().addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent fe) {
                
                
            }
            @Override
            public void focusLost(FocusEvent fe) {
                if (!campoRutPaciente.isValido()) {
                    cambiarEtiquetaMensajeria("Rut no válido", Color.black);
                    campoRutPaciente.getRut().requestFocus();
                } else {
                    service.Paciente paciente = (service.Paciente) cargarPaciente(campoRutPaciente.getRut().getText());
                    if (paciente == null) {
                        int confirmado = JOptionPane.showConfirmDialog(null, "El paciente no esta registrado, ¿desea hacerlo?");
                        if (JOptionPane.OK_OPTION == confirmado) {
                            try {
                                DialogoInfoPaciente dip = new DialogoInfoPaciente(null, true, null);
                                dip.setLocationRelativeTo(null);
                                dip.limpiarCampos();
                                dip.setTitle("Agregar Paciente");
                                dip.getBotonAceptar().setText("Agregar");
                                dip.getBotonAceptar().setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
                                dip.getBotonCancelar().setText("Cancelar");
                                dip.rut.getRut().setText(campoRutPaciente.getRut().getText());
                                dip.setVisible(true);
                                campoNombrePaciente.setText(dip.campoNombres.getText() + " " + dip.campoApellidoPat.getText() + " " + dip.campoApellidoMat.getText());                                
                            } catch (FileNotFoundException ex) {
                                Logger.getLogger(DialogoAgregarCita.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IOException ex) {
                                Logger.getLogger(DialogoAgregarCita.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } else {
                            campoRutPaciente.getRut().requestFocus();
                        }

                    } else {
                        campoNombrePaciente.setText(paciente.getNombres() + " " + paciente.getApellidoPaterno() + " " + paciente.getApellidoMaterno());                        
                    }
                }
            }
        });        
    }

    public void desactivaCheckPopups() {
        if (!lunes.isSelected()) {
            this.lunes.setEnabled(false);
        }
        if (!martes.isSelected()) {
            this.martes.setEnabled(false);
        }
        if (!miercoles.isSelected()) {
            this.miercoles.setEnabled(false);
        }
        if (!jueves.isSelected()) {
            this.jueves.setEnabled(false);
        }
        if (!viernes.isSelected()) {
            this.viernes.setEnabled(false);
        }
        if (!sabado.isSelected()) {
            this.sabado.setEnabled(false);
        }
    }

    public void activaCheckPopups() {
        this.lunes.setEnabled(true);
        this.martes.setEnabled(true);
        this.miercoles.setEnabled(true);
        this.jueves.setEnabled(true);
        this.viernes.setEnabled(true);
        this.sabado.setEnabled(true);
    }

    public boolean camposValidos() {
        boolean isValido = true;
        String mensaje = "";
        if (!campoRutPaciente.isValido()) {
            if (mensaje.equals("")) {
                mensaje = "Rut inválido";
            } else {
                mensaje = mensaje + ", rut inválido";
            }
            isValido = false;
        }        
        if (!campoNumeroSesion.getText().equals("") && contador > Integer.parseInt(campoNumeroSesion.getText()) - 1) {
            if (mensaje.equals("")) {
                mensaje = "Exiten mas repeticiones que número de sesiones";
            } else {
                mensaje = mensaje + ", exiten mas repeticiones que número de sesiones";
            }
            isValido = false;
        }
        if (!isValido) {
            this.campoMensajeria.setText(mensaje);
        }
        return isValido;
    }

    public ArrayList<Date> calculaFechasDeCitas() {
        ArrayList<Date> dates = new ArrayList<Date>();        
        Date actual = null;
        if (tipo.equals("Dia")) {
            actual = campoFecha.getDate();
        }
        if (tipo.equals("Semana")) {
            actual = campoFecha.getDate();
        }
        dates.add(actual);
        Calendar nextDate = new GregorianCalendar();
        nextDate.setTime(actual);
        boolean ningunoSeleccionado = !lunes.isSelected() && !martes.isSelected() && !miercoles.isSelected() && !jueves.isSelected() && !viernes.isSelected() && !sabado.isSelected();
        int cont = 0;
        while (!ningunoSeleccionado && cont < Integer.parseInt(this.campoNumeroSesion.getText()) - 1) {
            nextDate.add(Calendar.DAY_OF_MONTH, 1);
            if (nextDate.get(Calendar.DAY_OF_WEEK) == 2 && this.lunes.isSelected()) {
                dates.add(nextDate.getTime());
                cont++;
            }
            if (nextDate.get(Calendar.DAY_OF_WEEK) == 3 && this.martes.isSelected()) {
                dates.add(nextDate.getTime());
                cont++;
            }
            if (nextDate.get(Calendar.DAY_OF_WEEK) == 4 && this.miercoles.isSelected()) {
                dates.add(nextDate.getTime());
                cont++;
            }
            if (nextDate.get(Calendar.DAY_OF_WEEK) == 5 && this.jueves.isSelected()) {
                dates.add(nextDate.getTime());
                cont++;
            }
            if (nextDate.get(Calendar.DAY_OF_WEEK) == 6 && this.viernes.isSelected()) {
                dates.add(nextDate.getTime());
                cont++;
            }
            if (nextDate.get(Calendar.DAY_OF_WEEK) == 7 && this.sabado.isSelected()) {
                dates.add(nextDate.getTime());
                cont++;
            }
        }
        return dates;
    }

    private void formatoHora(int duracionBloques, String string) {
        String[] h = string.split(":");
        int inicioHora = Integer.parseInt(horario.getHoraInicio()), inicioMin = Integer.parseInt(horario.getMinInicio()), terminoHora = Integer.parseInt(horario.getHoraTermino()), terminoMin = Integer.parseInt(horario.getMinTermino());
        int bloquesTotal = ((terminoHora - inicioHora) * 60 + (terminoMin - inicioMin)) / duracionBloques;
        Object[] itemsHora = new Object[bloquesTotal];
        Object[] itemsMin = new Object[bloquesTotal];
        for (int i = 0; i < bloquesTotal; i++) {
            String hora = "", min = "";
            if (inicioHora < 10) {
                hora = "0" + inicioHora;
            } else {
                hora = "" + inicioHora;
            }
            if (inicioMin < 10) {
                min = "0" + inicioMin;
            } else {
                min = "" + inicioMin;
            }
            if (hora(itemsHora, hora, i)) {
                itemsHora[i] = hora;
            }
            if (min(itemsMin, min, i)) {
                itemsMin[i] = min;
            }
            if (inicioMin < 60) {
                inicioMin += duracionBloques;
            }
            if (inicioMin == 60) {
                inicioMin = 0;
                inicioHora += 1;
            }
            if (inicioMin > 60) {
                inicioMin = inicioMin - 60;
                inicioHora += 1;
            }
        }
        this.campoHora.setModel(new DefaultComboBoxModel(itemsHora));
        this.campoMinuto.setModel(new DefaultComboBoxModel(itemsMin));
        this.campoHora.setSelectedItem(h[0]);
        this.campoMinuto.setSelectedItem(h[1]);
    }

    public boolean hora(Object[] horas, String hr, int tamaño) {
        for (int i = 0; i < tamaño - 1; i++) {
            if (((String) horas[i]).equals(hr)) {
                return false;
            }
        }
        return true;
    }

    public boolean min(Object[] minutos, String min, int tamaño) {
        for (int i = 0; i < tamaño - 1; i++) {
            if (((String) minutos[i]).equals(min)) {
                return false;
            }
        }
        return true;
    }

    public void normalizarMensajeria() {
        campoMensajeria.setText("Área de mensajería");
        campoMensajeria.setForeground(Color.black);
    }

    public void cambiarEtiquetaMensajeria(String mensaje, Color color) {
        campoMensajeria.setText(mensaje);
        campoMensajeria.setForeground(color);
    }
    private void cargarProgramas(){
        campoProgramaMedico.removeAllItems();
        campoProgramaMedico.addItem("Sin programa");
        List<service.ProgramaMedicoFonasa> f = buscarProgramasFonasaDePaciente(campoRutPaciente.getRut().getText());
        List<service.ProgramaDipreca> d = buscarProgramasDiprecaDePaciente(campoRutPaciente.getRut().getText());
        List<service.ProgramaMedicoJeafosale> j = buscarProgramasJeafosaleDePaciente(campoRutPaciente.getRut().getText());
        for(int i = 0 ; i<f.size() ; i++){
            campoProgramaMedico.addItem(f.get(i));            
        }
        for(int i = 0 ; i<d.size() ; i++){
            campoProgramaMedico.addItem(d.get(i));            
        }
        for(int i = 0 ; i<j.size() ; i++){
            campoProgramaMedico.addItem(j.get(i));            
        }
        campoProgramaMedico.setRenderer(new RenderJCombobox());
    }
    private Cita agregarProgramaMedico(Cita cita) {
        Object o = campoProgramaMedico.getSelectedItem();
        if(o instanceof String){
            cita.setIdPrograma("Sin programa");
            cita.setTipoPrograma("Sin programa");
        }
        if(o instanceof service.ProgramaDipreca){
            service.ProgramaDipreca p = (service.ProgramaDipreca)o;
            cita.setIdPrograma(p.getNumeroPrograma());
            cita.setTipoPrograma("DIPRECA");
            p.setCantidadCitas(p.getCantidadCitas()-1);
            if(p.getCantidadCitas()==0)
                p.setVisible(false);
            modificarProgramaDipreca(p);
        }
        if(o instanceof service.ProgramaMedicoFonasa){
            service.ProgramaMedicoFonasa p = (service.ProgramaMedicoFonasa)o;
            cita.setIdPrograma(p.getNumeroPrograma());
            cita.setTipoPrograma("FONASA");              
            p.setCantidadCitas(p.getCantidadCitas()-1);
            if(p.getCantidadCitas()==0)
                p.setVisible(false);
            modificarProgramaFonasa(p);
        }
        if(o instanceof service.ProgramaMedicoJeafosale){
            service.ProgramaMedicoJeafosale p = (service.ProgramaMedicoJeafosale)o;
            cita.setIdPrograma(p.getNumeroPrograma());
            cita.setTipoPrograma("JEAFOSALE");
            p.setCantidadCitas(p.getCantidadCitas()-1);
            if(p.getCantidadCitas()==0)
                p.setVisible(false);
            modificarProgramaJeafosale(p);
        } 
        return cita;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonCrearPrograma;
    private javax.swing.JComboBox campoEstado;
    private com.toedter.calendar.JDateChooser campoFecha;
    private javax.swing.JComboBox campoHora;
    private javax.swing.JLabel campoMensajeria;
    private javax.swing.JComboBox campoMinuto;
    public javax.swing.JTextField campoNombrePaciente;
    private javax.swing.JTextField campoNumeroSesion;
    private javax.swing.JComboBox campoProgramaMedico;
    public componentes.Rut campoRutPaciente;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
    private com.toedter.calendar.JDayChooser jDayChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JCheckBox jueves;
    private javax.swing.JCheckBox lunes;
    private javax.swing.JCheckBox martes;
    private javax.swing.JCheckBox miercoles;
    private javax.swing.JCheckBox sabado;
    private javax.swing.JCheckBox viernes;
    // End of variables declaration//GEN-END:variables
   
    private static Long registrar(service.Usuario usuario, java.lang.String modulo, java.lang.String accion, java.lang.String valorAnterior, java.lang.String valorNuevo) {
        service.BitacoraWSService service = new service.BitacoraWSService();
        service.BitacoraWS port = service.getBitacoraWSPort();
        return port.registrar(usuario, modulo, accion, valorAnterior, valorNuevo);
    }

    private static Object cargarHorarioSegunFecha(javax.xml.datatype.XMLGregorianCalendar fecha, java.lang.String rut) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.cargarHorarioSegunFecha(fecha, rut);
    }

    private static Object cargarPaciente(java.lang.String rut) {
        service.PacienteWS_Service service = new service.PacienteWS_Service();
        service.PacienteWS port = service.getPacienteWSPort();
        return port.cargarPaciente(rut);
    }

    private static boolean agregarEnlaceProfesionalPaciente(java.lang.String rutProfesional, java.lang.String rutPaciente) {
        service.EnlaceProfesionalPacienteWSService service = new service.EnlaceProfesionalPacienteWSService();
        service.EnlaceProfesionalPacienteWS port = service.getEnlaceProfesionalPacienteWSPort();
        return port.agregarEnlaceProfesionalPaciente(rutProfesional, rutPaciente);
    }

    private static boolean isPacienteEnlazadoAProfesional(java.lang.String rutPaciente, java.lang.String rutProfesional) {
        service.EnlaceProfesionalPacienteWSService service = new service.EnlaceProfesionalPacienteWSService();
        service.EnlaceProfesionalPacienteWS port = service.getEnlaceProfesionalPacienteWSPort();
        return port.isPacienteEnlazadoAProfesional(rutPaciente, rutProfesional);
    }

    
    class RenderJCombobox implements ListCellRenderer{        
        DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
        @Override
        public Component getListCellRendererComponent(JList jlist, Object e, int i, boolean bln, boolean bln1) {            
            JLabel label= (JLabel) defaultRenderer.getListCellRendererComponent(jlist, e, i, bln, bln1);
            if(e instanceof String){            
                label.setText((String)e);
            }
            if(e instanceof service.ProgramaDipreca){            
                label.setText(((service.ProgramaDipreca)e).getNumeroPrograma()+" - "+"DIPRECA");
            }
            if(e instanceof service.ProgramaMedicoFonasa){            
                label.setText(((service.ProgramaMedicoFonasa)e).getNumeroPrograma()+" - "+"FONASA");
            }
            if(e instanceof service.ProgramaMedicoJeafosale){
                label.setText(((service.ProgramaMedicoJeafosale)e).getNumeroPrograma()+" - "+"JEAFOSALE");
            }
            
            return label;
        }
    }

    
    private static Long agregarCita(service.Cita cita) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.agregarCita(cita);
    }    

    

    private static java.util.List<service.ProgramaDipreca> buscarProgramasDiprecaDePaciente(java.lang.String rutPaciente) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.buscarProgramasDiprecaDePaciente(rutPaciente);
    }

    private static java.util.List<service.ProgramaMedicoFonasa> buscarProgramasFonasaDePaciente(java.lang.String rutPaciente) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.buscarProgramasFonasaDePaciente(rutPaciente);
    }

    private static java.util.List<service.ProgramaMedicoJeafosale> buscarProgramasJeafosaleDePaciente(java.lang.String rutPaciente) {
        service.AgendaWS_Service service = new service.AgendaWS_Service();
        service.AgendaWS port = service.getAgendaWSPort();
        return port.buscarProgramasJeafosaleDePaciente(rutPaciente);
    }

    private static boolean modificarProgramaJeafosale(service.ProgramaMedicoJeafosale programaDipreca) {
        service.ProgramaJeafosaleWSService service = new service.ProgramaJeafosaleWSService();
        service.ProgramaJeafosaleWS port = service.getProgramaJeafosaleWSPort();
        return port.editarProgramaJeafosale(programaDipreca);
    }

    private static boolean modificarProgramaDipreca(service.ProgramaDipreca programaDipreca) {
        service.ProgramaDiprecaWSService service = new service.ProgramaDiprecaWSService();
        service.ProgramaDiprecaWS port = service.getProgramaDiprecaWSPort();
        return port.editarProgramaDipreca(programaDipreca);
    }

    private static boolean modificarProgramaFonasa(service.ProgramaMedicoFonasa programaMedico) {
        service.ProgramaFonasaWSService service = new service.ProgramaFonasaWSService();
        service.ProgramaFonasaWS port = service.getProgramaFonasaWSPort();
        return port.modificarProgramaFonasa(programaMedico);
    }

    
    

   
}
